<?php
/*
Plugin Name: Entries group with tags for TC
Version: 0.1
Author: Cain Chen, Hinablue.
Author URI: http://hina.ushiisland.net/blog/hinablue/
*/ 

function EntriesWithTags($target, $mother) {
	global $suri, $defaultURL, $blogURL, $pluginURL, $configVal, $blog, $service, $blogid, $database;
	requireComponent('Textcube.Function.misc');

	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
	switch($blog['blogLanguage']) {
		case "zh-TW":
			$text[0] = "相關文章";
			$text[1] = "沒有相關文章。";
		break;
		case "zh-CN":
			$text[0] = "相关文章";
			$text[1] = "没有相关文章。";
		break;
		default:
			$text[0] = "Related entries";
			$text[1] = "No related entries.";
	}	
	
	$html = '';
	if($suri['directive']!="/rss" && $suri['directive']!="/atom" && $suri['directive']!="/m" && $suri['directive']!="/i/entry" && $suri['directive']!="/sync") {

		$html = <<<EOF
		<div class="entriesWithTags">
			<fieldset style="margin:20px 0px 20px 0px;padding:5px;border:1px solid #efefef;">
				<legend>&nbsp;{$text[0]}&nbsp;</legend>
				<ul id="entrieswithtags">
EOF;

		$data = misc::fetchConfigVal($configVal);
		$category = DBQuery::queryCell("SELECT category FROM {$database['prefix']}Entries WHERE blogid = {$blogid} AND id = {$mother}");
		$entries = isset($data['entries']) ? $data['entries'] : 5;
		$entries = DBQuery::queryColumn("SELECT r.entry FROM {$database['prefix']}TagRelations AS r INNER JOIN {$database['prefix']}Entries AS e ON e.category={$category} AND e.id=r.entry WHERE r.blogid = {$blogid} AND r.tag IN (SELECT tag FROM {$database['prefix']}TagRelations WHERE blogid = {$blogid} AND entry = {$mother}) AND r.entry != {$mother} GROUP BY r.entry ORDER BY r.entry DESC LIMIT {$entries}");
		if(count((array)$entries)>0) {
			foreach((array)$entries as $id) {
				$title		= DBQuery::queryCell("SELECT title FROM {$database['prefix']}Entries WHERE blogid = {$blogid} AND id = {$id}");
				$slogan		= rawurlencode(DBQuery::queryCell("SELECT slogan FROM {$database['prefix']}Entries WHERE blogid = {$blogid} AND id = {$id}"));
				if ($suri['directive']=="/category") {
					$permalink	= ($blog['useSloganOnCategory']) ? "{$defaultURL}/entry/{$slogan}" : "{$defaultURL}/{$id}";
				} elseif ($suri['directive']=="/tag") {
					$permalink	= ($blog['useSloganOnTag']) ? "{$defaultURL}/entry/{$slogan}" : "{$defaultURL}/{$id}";
				} else {
					$permalink	= ($blog['useSloganOnPost']) ? "{$defaultURL}/entry/{$slogan}" : "{$defaultURL}/{$id}";
				}
				$html .= "<li><a href=\"{$permalink}\">{$title}</a></li>";
			}
		} else {
			$html .= "<li>{$text[1]}</li>";
		}	
	$html .= <<<EOF
			</ul>
		</fieldset>
	</div>
EOF;
	}
	return $target.$html;
}

function EntriesWithTags_DataSet($data) {
	requireComponent('Textcube.Function.misc');
	$cfg = misc::fetchConfigVal($data);
	if(!$cfg['entries'] || empty($cfg['entries']) || intval($cfg['entries']<=0)) $cfg['entries'] = 5;
	return true;
}
?>